package com.example.dfa;

import java.util.*;

public class SensitiveWordUtils {
    public static Map<String, Object> sensitiveMap=new HashMap<>();

    public static void initMap(List<String> wordsList){
        if (wordsList.size()==0){
            System.out.println("敏感词不能为空");
            return;
        }
        /**
         * 给足够的容量.避免扩容
         * 声明一个指针
         */
        Map<String, Object> map = new HashMap<>(wordsList.size());
        Map<String, Object> curMap=null;
        /**
         * 迭代器遍历敏感词列表
         */
        Iterator<String> iterator= wordsList.iterator();
        while (iterator.hasNext()){
            String word = iterator.next();
            int len=word.length();
            curMap=map;
            /**
             * 遍历此敏感词
             */
            for (int i = 0; i <len; i++) {
                String key=String.valueOf(word.charAt(i));
                Map<String, Object> wordMap= (Map<String, Object>) curMap.get(key);
                if (wordMap==null){
                    wordMap=new HashMap<>(2);
                    wordMap.put("isEnd","0");
                    curMap.put(key,wordMap);
                }
                curMap=wordMap;
                if (i==len-1){
                    curMap.put("isEnd","1");
                }
            }
        }
        //给词库赋值
        sensitiveMap=map;
    }

    public static Map<String, Integer> match(String text){
        Map<String, Integer> map=new HashMap<>();
        for (int i = 0; i < text.length(); i++) {
            int wordLen=check(text,i);
            if (wordLen>0){
                String word = text.substring(i, i+wordLen);
                if (map.containsKey(word)){
                    map.put(word,map.get(word)+1);
                }else {
                    map.put(word,1);
                }
                i+=wordLen-1;
            }
        }
        return map;
    }

    public static int check(String text, int beginIndex) {
        if (sensitiveMap==null){
            throw new RuntimeException("敏感词库不能为空");
        }
        boolean isEnd=false;
        int wordLen=0;
        Map<String, Object> curMap=sensitiveMap;
        for (int i = beginIndex; i < text.length(); i++) {
            String key = String.valueOf(text.charAt(i));
            curMap= (Map<String, Object>) curMap.get(key);
            if (curMap==null){
                break;
            }else {
                wordLen++;
                if ("1".equals(String.valueOf(curMap.get("isEnd")))){
                    isEnd=true;
                }
            }
        }
        if (!isEnd){
            wordLen=0;
        }
        return wordLen;
    }

    public static void main(String[] args) {
        List<String> list= Arrays.asList("法轮功","法轮","冰毒");
        initMap(list);
        System.out.println(sensitiveMap);
        Map<String, Integer> map = match("法轮功法轮真的不好，冰毒与法轮功都不好");
        System.out.println(map);
    }
}
